<?php

namespace app\components;


use app\exception\BuyException;
use app\exception\ErrorCode;
use app\exception\OaException;
use app\service\UserService;
use yii\validators\Validator;

class CodeValidator extends Validator
{
    /**
     * @param \yii\base\Model $model
     * @param string $attribute
     * @throws BuyException
     */
    public function validateAttribute($model, $attribute)
    {
        $redis = UserService::getRedis();
        $value = $model->$attribute;
        $phone = $model->phone;

        $checkNumKey = "ERR_CHECK".$phone;



        $fob = $redis->get($checkNumKey."2");
        if ($fob) {
            throw new OaException(ErrorCode::USER_CHECK_ERR);
        }

        if (!$phone || !$value) {
            throw new OaException(ErrorCode::PARMA_ERROR);
        }
        $code= $redis->get(\Yii::$app->params["CODE_FIX"].$phone);
        if (strtolower($value)!=strtolower($code)) {

            $redis->incr($checkNumKey);
            $redis->expire($checkNumKey,3600);

            if (intval($redis->get($checkNumKey))>=5) {
                $redis->set($checkNumKey."2",1);
                $redis->set($checkNumKey."2",3600*24);
            }


            throw new OaException(ErrorCode::CODE_ERR);
        }
    }
}